/*
 * @Author: 肖芬芳 1911683843@qq.com
 * @Date: 2022-11-30 11:24:02
 * @LastEditors: 肖芬芳 1911683843@qq.com
 * @LastEditTime: 2022-11-30 16:35:13
 * @FilePath: \blog\routes\admin\modifyPassword.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
const { User } = require('../../model/user');
const { ObjectId } = require('mongodb');
// 对象规则验证
const Joi = require('joi');
// hash密码
const bcrypt = require('bcryptjs');

module.exports = async (req, res) => {
    // console.log(req.fields)
    const salt = await bcrypt.genSalt(10);
    let user=await User.findOne({_id:ObjectId(req.fields.id)})
    if(user){
        let isValidate = await bcrypt.compare(req.fields.password, user.password);
        if(!isValidate){
            res.send({ 'code': 1, "msg": "原密码填写错误！" });
        }else{
            // 使用盐对密码进行加密
            let newPassword=await bcrypt.hash(req.fields.newPassword, salt);
            let {modifiedCount:modifiedCount}=await User.updateOne({_id:ObjectId(req.fields.id)},{$set:{password:newPassword}})
            if(modifiedCount==1){
                res.send({ 'code': 0, "msg": "修改成功" });
            }else{
                res.send({ 'code': 1, "msg": "修改失败" });
            }
        }
    }
}